package com.ysstech.finance.service.impl;

import java.time.LocalDateTime;
import java.util.*;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ysstech.common.entity.Dicvalue;
import com.ysstech.common.entity.TreeNode;
import com.ysstech.common.enums.YssEnum;
import com.ysstech.common.service.DicvalueService;
import com.ysstech.common.util.DateUtil;
import com.ysstech.finance.entity.Subject;
import com.ysstech.finance.mapper.SubjectMapper;
import com.ysstech.finance.service.SubjectService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lishuangliang
 * @since 2021-03-10
 */
@Slf4j
@Service
public class SubjectServiceImpl extends ServiceImpl<SubjectMapper, Subject> implements SubjectService {
    /**
     * 查询科目树
     *
     * @return
     * @throws Exception
     */
    public List<TreeNode> querySubjectTree(Subject subject) throws Exception {
        //directionSubjectTemplate();
        List<TreeNode> list = new ArrayList<>();
        Map<String, List<Subject>> map = getSubjectMapByProjectId(subject);
        if (null == subject || StringUtils.isBlank(subject.getParentId())) {
            list.addAll(this.getTreeNode("0", map));
        } else {
            list.addAll(this.getTreeNode(subject.getParentId(), map));
        }

        return list;
    }

    @Override
    public Map<String, Subject> getSubjectMap() throws Exception {
        Map<String, Subject> map = new HashMap<>();
        List<Subject> list = this.list();
        if (CollectionUtils.isEmpty(list)) {
            return map;
        }
        for (Subject subject : list) {
            if (null == subject) {
                continue;
            }
            map.put(subject.getId(), subject);
        }
        return map;
    }

    public Map<String, List<Subject>> getSubjectMapByProjectId(Subject subject) throws Exception {
        Map<String, List<Subject>> map = new LinkedHashMap<>();
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        if (null == subject) {
            return map;
        }
        wrapper.eq("PROJECT_ID", subject.getProjectId());
        if (StringUtils.isNotBlank(subject.getStrAssetsType())) {
            wrapper.eq("ASSETS_TYPE", Integer.valueOf(subject.getStrAssetsType()));
        }
        if (StringUtils.isNotBlank(subject.getStrAmount())) {
            wrapper.eq("AMOUNT", Integer.valueOf(subject.getStrAmount()));
        }
        wrapper.orderByAsc("CODE");
        List<Subject> list = this.list(wrapper);
        if (CollectionUtils.isEmpty(list)) {
            return map;
        }
        for (Subject subject1 : list) {
            String key = subject1.getParentId();
            List<Subject> listSubject = null;
            if (map.containsKey(key)) {
                listSubject = map.get(key);
                if (CollectionUtils.isEmpty(listSubject)) {
                    continue;
                }
                listSubject.add(subject1);
                map.put(key, listSubject);
            } else {
                listSubject = new ArrayList<>();
                listSubject.add(subject1);
                map.put(key, listSubject);
            }
        }
        return map;
    }

    /**
     * 递归查询科目信息的方法
     *
     * @param parentMenuId
     * @return
     * @throws Exception
     */
    public List<TreeNode> getTreeNode(String parentMenuId, Map<String, List<Subject>> map) throws Exception {
        List<Subject> subjects = null;
        for (Map.Entry<String, List<Subject>> info : map.entrySet()) {
            if (parentMenuId.equals(info.getKey())) {
                subjects = info.getValue();
                break;
            }
        }
        List<TreeNode> list = new ArrayList<>();
        if (CollectionUtils.isEmpty(subjects)) {
            return list;
        }
        for (Subject bean : subjects) {
            if (null == bean) {
                continue;
            }
            TreeNode treeNode = subjectToNode(bean);
            List<TreeNode> children = getTreeNode(bean.getId(), map);
            if (null == children || children.size() == 0) {
                treeNode.setState("open");  // 没有子节点的
            }
            treeNode.setChildren(children);
            list.add(treeNode);
        }
        return list;
    }

    /**
     * 将业务功能转化成TreeNode
     */

    protected TreeNode subjectToNode(Subject subject) {
        TreeNode node = new TreeNode();
        node.setId(subject.getId());
        node.setText(subject.getCode() + "_" + subject.getName());
        node.setIconCls("icon-bricks");
        node.setState("closed");
        if (null != subject.getDetailed() && 1 == subject.getDetailed()) {
            node.setState("open");
        }
        node.setChecked(false);
        node.setMenuLevel(subject.getDetailed());
        node.setPId(subject.getParentId());
        node.setAttributes(subject.getCode());
        return node;
    }


    @Autowired
    private DicvalueService dicvalueService;

    /**
     * 生成科目模板信息，方案id为0的数据
     *
     * @throws Exception
     */
    @Transactional
    public void directionSubjectTemplate() throws Exception {
        List<Subject> addlist = new ArrayList<>();
        //金融工具分类-上市和流通情况
        String adjustCode = "INVESTMENT@LISTINGANDCIRCULATION@核算分类@TRANSACTION_ATTRIBUTE";
        List<String> list = Arrays.asList(adjustCode.split("@")); //核算项
        Subject subject = new Subject();
        subject.setCode("1002");
        subject.setName("银行存款");
        subject.setAssetsType(1);
        subject.setDrandcr("DR");
        subject.setAmount(1);
        subject.setProjectId("yss");
        subject.setDetailed(2);
        subject.setParentId("0");
        //subject.setAdjustCode(null);
        subject.setId(DateUtil.generateUUID());
        subject.setAddTime(LocalDateTime.now());
        addlist.add(subject);
        if (CollectionUtils.isEmpty(list)) {
            subject.setDetailed(1); //没有核算项就设置该科目为明细科目
        }
        recursionAdjust(subject, list, addlist, 0);
        QueryWrapper<Subject> wrapper = new QueryWrapper<>();
        wrapper.like("CODE", "1002");
        wrapper.eq("PROJECT_ID", "yss");
        this.remove(wrapper);
        this.saveBatch(addlist);
    }


    private void recursionAdjust(Subject subject, List<String> list0, List<Subject> addlist, int i) throws Exception {
        if (i >= list0.size()) {
            return;
        }
        List<Dicvalue> dicvalueList = dicvalueService.getCacheDicValueList(list0.get(i));
        if ("核算分类".equals(list0.get(i))) {
            dicvalueList = new ArrayList<>();
            Dicvalue dicvalue = new Dicvalue();
            dicvalue.setValue("01");
            dicvalue.setShowmsg("成本|面值");
            dicvalueList.add(dicvalue);
            Dicvalue dicvalue2 = new Dicvalue();
            dicvalue2.setValue("02");
            dicvalue2.setShowmsg("估值增值");
            dicvalueList.add(dicvalue2);
          /* Dicvalue dicvalue3 = new Dicvalue();
            dicvalue3.setValue("03");
            dicvalue3.setShowmsg("溢折价");
            dicvalueList.add(dicvalue3);*/
         /*   Dicvalue dicvalue4 = new Dicvalue();
            dicvalue4.setValue("04");
            dicvalue4.setShowmsg("减值准备");
            dicvalueList.add(dicvalue4);*/
        }
        if (CollectionUtils.isEmpty(dicvalueList)) {
            return;
        }
        for (Dicvalue dicvalue : dicvalueList) {
            if (null == dicvalue) {
                continue;
            }
            String maincode2 = subject.getCode() + "." + dicvalue.getValue();
            String adjustcode2 = list0.get(i);
           /* if (StringUtils.isNotBlank(subject.getAdjustCode())) {
                adjustcode2 = subject.getAdjustCode() + "-" + list0.get(i);
            }*/
            Subject subject2 = new Subject();
            subject2.setAssetsType(subject.getAssetsType());
            subject2.setDrandcr(subject.getDrandcr());
            subject2.setAmount(subject.getAmount());
            subject2.setProjectId("yss");
            subject2.setDetailed(subject.getDetailed());
            if (i == list0.size() - 1) {
                subject2.setDetailed(1);
            }
            // subject2.setAdjustCode(adjustcode2);
            subject2.setCode(maincode2);
            subject2.setName(subject.getName() + "-" + dicvalue.getShowmsg());
            subject2.setId(DateUtil.generateUUID());
            subject2.setAddTime(LocalDateTime.now());
            subject2.setParentId(subject.getId());
            addlist.add(subject2);
            recursionAdjust(subject2, list0, addlist, i + 1);
        }
    }

}
